package com.shinhye.mobilelottery.ui.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Vibrator;

public abstract class ShakeListener implements SensorEventListener {
	private float lastX;
	private float lastY;
	private float lastZ;
	private long lasttime;
	private int duration = 100;
	private float totalDelta = 0;
	private int threshold = 200;
	private Vibrator vibrator;
	
	private void init() {
		lastX = 0;
		lastY = 0;
		lastZ = 0;
		lasttime = 0;
		totalDelta = 0;
	}
	
	public ShakeListener(Context context) {
		vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
	}
	
	@Override
	public void onSensorChanged(SensorEvent event) {
		//第一次传感器获取数据
		if(lasttime == 0) {
			lastX = event.values[0];
			lastY = event.values[1];
			lastZ = event.values[2];
			lasttime = System.currentTimeMillis();
		} else {
			long currtime = System.currentTimeMillis();
			if((currtime - lasttime) >= duration) {
				float x = event.values[0];
				float y = event.values[1];
				float z = event.values[2];
				
				float dx = Math.abs(x - lastX);
				dx = dx < 1 ? 0 : dx;
				float dy = Math.abs(y - lastY);
				dy = dy < 1 ? 0 : dy;
				float dz = Math.abs(z - lastZ);
				dz = dz < 1 ? 0 : dz;
				
				float shake = dx + dy + dz;
				if(shake == 0) {
					init();
				}
				
				totalDelta += shake;
				
				if(totalDelta >= threshold) {
					//震动手机
					vibrator.vibrate(100);
					shaked();
					init();
				} else {
					lastX = event.values[0];
					lastY = event.values[1];
					lastZ = event.values[2];
					lasttime = System.currentTimeMillis();
				}
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {}

	public abstract void shaked();
}
